package cn.kite.service.impl;

import cn.kite.annotation.TransactionSupport;
import cn.kite.mapper.ds1.UserMapper;
import cn.kite.mapper.ds2.ScoreMapper;
import cn.kite.model.ds1.UserDO;
import cn.kite.model.ds2.ScoreDO;
import cn.kite.service.ITestService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kite
 * @description
 * @date 2020/11/10
 */
@Service
@TransactionSupport(value = {"ds1TrManager", "ds2TrManager"})
public class TestServiceImpl implements ITestService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ScoreMapper scoreMapper;

    @Override
    public Object select() {
        UserDO userDO = userMapper.selectById(1);
        LambdaQueryWrapper<ScoreDO> query = Wrappers.lambdaQuery(ScoreDO.class).eq(ScoreDO::getUserId, userDO.getId());
        List<ScoreDO> scoreDOList = scoreMapper.selectList(query);
        Map<String, Object> res = new HashMap<>();
        res.put("user", userDO);
        res.put("score", scoreDOList);
        return res;
    }

    //@TransactionSupport(value = {"ds1TrManager", "ds2TrManager"})
    @Override
    public Object save(boolean tr) throws Exception {
        UserDO userDO = new UserDO();
        userDO.setName("测试用户");
        userMapper.insert(userDO);
        ScoreDO scoreDO = new ScoreDO();
        scoreDO.setUserId(userDO.getId());
        scoreDO.setScore(100);
        scoreMapper.insert(scoreDO);
        if(tr){
            throw new Exception("测试异常事务回滚");
        }
        return "ok";
    }
}
